using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using DocumentCreationSystem.Services;
using DocumentCreationSystem.Models;
using System.Text.Json;
using System.IO;

namespace DocumentCreationSystem;

/// <summary>
/// 测试GPU监控功能
/// </summary>
public class TestGpuMonitor
{
    public static async Task Main(string[] args)
    {
        // 设置服务
        var services = new ServiceCollection();
        services.AddLogging(builder => builder.AddConsole().SetMinimumLevel(LogLevel.Information));
        services.AddHttpClient();
        
        // 添加配置
        var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: false)
            .Build();
        services.AddSingleton<IConfiguration>(configuration);
        
        // 添加AI配置服务
        services.AddScoped<IAIModelConfigService, AIModelConfigService>();
        services.AddScoped<IAIService, AIServiceManager>();
        services.AddScoped<ISystemMonitorService, SystemMonitorService>();
        
        var serviceProvider = services.BuildServiceProvider();
        var logger = serviceProvider.GetRequiredService<ILogger<TestGpuMonitor>>();
        var monitorService = serviceProvider.GetRequiredService<ISystemMonitorService>();

        try
        {
            logger.LogInformation("=== GPU监控功能测试 ===");
            
            // 1. 测试GPU基本信息获取
            logger.LogInformation("1. 获取GPU基本信息...");
            var gpuInfo = await monitorService.GetGpuInfoAsync();
            
            logger.LogInformation($"GPU可用: {gpuInfo.IsAvailable}");
            if (gpuInfo.IsAvailable)
            {
                logger.LogInformation($"GPU名称: {gpuInfo.Name}");
                logger.LogInformation($"GPU驱动版本: {gpuInfo.DriverVersion}");
                logger.LogInformation($"GPU显存总量: {gpuInfo.TotalMemoryMB / 1024.0:F1}GB");
            }
            else
            {
                logger.LogInformation("未检测到可用的GPU");
            }
            
            // 2. 测试GPU性能监控
            logger.LogInformation("\n2. 测试GPU性能监控...");
            if (gpuInfo.IsAvailable)
            {
                logger.LogInformation($"GPU使用率: {gpuInfo.UsagePercentage:F1}%");
                logger.LogInformation($"GPU显存已用: {gpuInfo.UsedMemoryMB / 1024.0:F1}GB");
                
                if (gpuInfo.TotalMemoryMB > 0)
                {
                    var memoryUsagePercentage = (double)gpuInfo.UsedMemoryMB / gpuInfo.TotalMemoryMB * 100;
                    logger.LogInformation($"GPU显存占用率: {memoryUsagePercentage:F1}%");
                }
                
                if (gpuInfo.Temperature.HasValue)
                {
                    logger.LogInformation($"GPU温度: {gpuInfo.Temperature.Value:F1}°C");
                }
                else
                {
                    logger.LogInformation("GPU温度: 未获取到");
                }
            }
            
            // 3. 测试完整系统资源监控
            logger.LogInformation("\n3. 测试完整系统资源监控...");
            var resourceInfo = await monitorService.GetSystemResourceInfoAsync();
            
            // CPU信息
            logger.LogInformation($"CPU: {resourceInfo.Cpu.Name}");
            logger.LogInformation($"CPU核心数: {resourceInfo.Cpu.CoreCount}");
            logger.LogInformation($"CPU使用率: {resourceInfo.Cpu.UsagePercentage:F1}%");
            
            // 内存信息
            logger.LogInformation($"内存总量: {resourceInfo.Memory.TotalMemoryMB / 1024.0:F1}GB");
            logger.LogInformation($"内存已用: {resourceInfo.Memory.UsedMemoryMB / 1024.0:F1}GB");
            logger.LogInformation($"内存使用率: {resourceInfo.Memory.UsagePercentage:F1}%");
            
            // GPU信息（再次验证）
            logger.LogInformation($"GPU可用: {resourceInfo.Gpu.IsAvailable}");
            if (resourceInfo.Gpu.IsAvailable)
            {
                logger.LogInformation($"GPU名称: {resourceInfo.Gpu.Name}");
                logger.LogInformation($"GPU使用率: {resourceInfo.Gpu.UsagePercentage:F1}%");
                
                if (resourceInfo.Gpu.TotalMemoryMB > 0)
                {
                    var memoryUsagePercentage = (double)resourceInfo.Gpu.UsedMemoryMB / resourceInfo.Gpu.TotalMemoryMB * 100;
                    logger.LogInformation($"GPU显存: {resourceInfo.Gpu.UsedMemoryMB / 1024.0:F1}GB/{resourceInfo.Gpu.TotalMemoryMB / 1024.0:F1}GB ({memoryUsagePercentage:F1}%)");
                }
                
                if (resourceInfo.Gpu.Temperature.HasValue)
                {
                    logger.LogInformation($"GPU温度: {resourceInfo.Gpu.Temperature.Value:F1}°C");
                }
            }
            
            // 4. 测试监控服务启动和数据更新
            logger.LogInformation("\n4. 测试监控服务实时更新...");
            var updateCount = 0;
            monitorService.MonitorDataUpdated += (sender, e) =>
            {
                updateCount++;
                logger.LogInformation($"监控数据更新 #{updateCount}:");
                logger.LogInformation($"  CPU使用率: {e.ResourceInfo.Cpu.UsagePercentage:F1}%");
                logger.LogInformation($"  内存使用率: {e.ResourceInfo.Memory.UsagePercentage:F1}%");
                
                if (e.ResourceInfo.Gpu.IsAvailable)
                {
                    logger.LogInformation($"  GPU使用率: {e.ResourceInfo.Gpu.UsagePercentage:F1}%");
                    if (e.ResourceInfo.Gpu.TotalMemoryMB > 0)
                    {
                        var memoryUsagePercentage = (double)e.ResourceInfo.Gpu.UsedMemoryMB / e.ResourceInfo.Gpu.TotalMemoryMB * 100;
                        logger.LogInformation($"  GPU显存占用率: {memoryUsagePercentage:F1}%");
                    }
                }
                
                if (updateCount >= 3)
                {
                    monitorService.StopMonitoring();
                    logger.LogInformation("监控测试完成，已停止监控");
                }
            };
            
            monitorService.StartMonitoring();
            logger.LogInformation("监控服务已启动，等待数据更新...");
            
            // 等待监控数据更新
            await Task.Delay(20000); // 等待20秒
            
            if (updateCount == 0)
            {
                logger.LogWarning("未收到监控数据更新，可能存在问题");
                monitorService.StopMonitoring();
            }
            
            logger.LogInformation("\n=== GPU监控功能测试完成 ===");
            
            // 5. 总结测试结果
            if (gpuInfo.IsAvailable)
            {
                logger.LogInformation("✅ GPU监控功能正常");
                logger.LogInformation($"   - 检测到GPU: {gpuInfo.Name}");
                logger.LogInformation($"   - 使用率监控: {(gpuInfo.UsagePercentage > 0 ? "正常" : "可能需要nvidia-smi")}");
                logger.LogInformation($"   - 显存监控: {(gpuInfo.TotalMemoryMB > 0 ? "正常" : "部分功能受限")}");
                logger.LogInformation($"   - 温度监控: {(gpuInfo.Temperature.HasValue ? "正常" : "不支持或需要nvidia-smi")}");
            }
            else
            {
                logger.LogInformation("⚠️  未检测到GPU或GPU监控功能受限");
                logger.LogInformation("   - 请确认系统中安装了独立显卡");
                logger.LogInformation("   - 对于NVIDIA显卡，建议安装nvidia-smi工具");
            }
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "GPU监控测试过程中发生错误");
        }
        
        Console.WriteLine("\n按任意键退出...");
        Console.ReadKey();
    }
}
